import React, { useState } from 'react';

import { Form, Input, Modal, Radio, Upload,message } from 'antd';
import { FormValueType, TreeNode } from '../data.d';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import styles from '../index.less';
import { useModel } from 'umi';
import { validTypeId } from '@/services/devicetype';
const FormItem = Form.Item;

export interface UpdateFormProps {
 
  onCancel: () => void;
  onSubmit: (values: FormValueType) => void;
  updateModalVisible: boolean;
  values: FormValueType;
}

const formLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 15 },
};

const UpdateForm: React.FC<UpdateFormProps> = (props) => {
  const [formVals, setFormVals] = useState<FormValueType>(props.values);
  
  

  const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false);
  const { updateModalVisible, onSubmit: handleUpdate,  onCancel} = props;

  const okHandle = async () => {
    const fieldsValue = await form.validateFields();
    fieldsValue.typeId= formVals.typeId;
    fieldsValue.typeImg=formVals.typeImg;
    fieldsValue.newtypeId=
    form.resetFields();
    
    console.log(fieldsValue)
    handleUpdate(fieldsValue);
  };
 
  const handleChange = (info: any) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
   
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      const pic = info.file.response
      
      setFormVals({ ...formVals, ...{ typeImg: pic.attachCode } });
      setLoading(false);
    }
  };

  const beforeUpload = (file: any) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传JPG/PNG文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图像必须小于2MB!');
    }
    return isJpgOrPng && isLt2M;
  }

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div className="ant-upload-text">上传图片</div>
    </div>
  );

  const validatorTypeId = async (_: any, value: string) => {

    const promise = Promise;
    if(value==null||value==""){
      return promise.reject("请输入typeId");
    }else if (value!=formVals.typeId) {
      const json = await validTypeId({  typeId:formVals.typeId, newTypeId: value });
      if(json=="数据重复"){
        return promise.reject(json);
      }
    }
    return promise.resolve();
  };

  return (
    <Modal
      width={640}
     
      destroyOnClose
      title="编辑设备类型"
      visible={updateModalVisible}
      onOk={okHandle}
      onCancel={() => onCancel()}
    >
      <Form
        {...formLayout}
        form={form}
        initialValues={{...formVals,newTypeId:formVals.typeId}}
      >

        <FormItem
          label="设备类型Id"
          name="newTypeId"
          rules={[{validator: validatorTypeId }]}
        >
          <Input placeholder="请输入" type={"number"} />
        </FormItem>
        <FormItem
          label="设备类型名称"
          name="typeName"
          rules={[{ required: true, message: '请输入至少三个字符！', min: 3 }]}
        >
          <Input placeholder="请输入" />
        </FormItem>
        <FormItem
          label="图标"
          name="typeImg"
        >
        <Upload
                name="file"
                listType="picture-card"
                showUploadList={false}
                className={styles.uploader}
               // headers={{ 'x-auth-token': getToken() }}
                action="/api/imageUpload"
                beforeUpload={beforeUpload}
                onChange={handleChange}
              >
                {formVals.typeImg ? <img src={'/img/' + formVals.typeImg} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
              </Upload>

        </FormItem>
        <FormItem
          label="设备类型描述"
          name="typeDescription"
        >
          <Input.TextArea rows={2} placeholder="请输入" />
        </FormItem>
        <FormItem
          label="表名称"
          name="tableName"
          rules={[{required: true, }]}
        >
          <Input placeholder="请输入" />
        </FormItem>
      </Form>
    </Modal>
  );
};

export default UpdateForm;
